<template>
    <div>
        <h4 style="color:deepskyblue;">养殖信息&ensp;&ensp;<el-button @click="Sultrueaddtion">设置</el-button>
        </h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="品种：">{{ form.breed }}</el-descriptions-item>
            <el-descriptions-item label="来源：">{{ form.source }}</el-descriptions-item>
            <el-descriptions-item label="饲养天数：">{{ form.feedingDays }}</el-descriptions-item>
            <el-descriptions-item label="饲养品牌：">{{ form.brand }}</el-descriptions-item>
            <el-descriptions-item label="饲养负责人：">{{ form.personIncharge }}</el-descriptions-item>
            <el-descriptions-item label="出栏日期：">{{ form.publicationDateTime }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:deepskyblue;">保健信息&ensp;&ensp;<el-button @click="addTable">新增行</el-button></h4>
        <!-- 免疫信息 -->
        <el-table :data="immuneList"
            :header-cell-style="{ backgroundColor: '#d6d6d6', color: '#000000', fontSize: '14px' }">
            <el-table-column label=" 饲养天数">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-input v-model.number="immuneInfo.feedingDays" />
                    </span>
                    <span v-else>
                        {{ scope.row.feedingDays }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="保健方式">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-input v-model="immuneInfo.healthCareMode" />
                    </span>
                    <span v-else>
                        {{ scope.row.healthCareMode }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="保健方法">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-input v-model="immuneInfo.healthCareMethod" />
                    </span>
                    <span v-else>
                        {{ scope.row.healthCareMethod }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template v-slot="scope">
                    <span v-if="scope.row.isShow">
                        <el-button @click="Addimmune()" v-for="button in buttonsuccess" :key="button.text"
                            :type="button.type" link>{{ button.text }}</el-button>
                        <el-button @click="DelTable()" v-for="button in buttoninfo" :key="button.text"
                            :type="button.type" link>{{ button.text }}</el-button>
                    </span>
                    <span v-else>
                        <el-button @click="scope.row.isShow = true, getimmuseinfo(scope.row.iId)"
                            v-for="button in buttonwarning" :key="button.text" :type="button.type" link>{{
                                button.text
                            }}</el-button>
                        <el-button @click="deltimmnue(scope.row.iId)" v-for="button in buttondanger" :key="button.text"
                            :type="button.type" link>{{ button.text }}</el-button>
                    </span>
                </template>
            </el-table-column>
        </el-table>
        <br />
        <hr /><br />
        <!-- 养殖信息 -->
        <br /> <br />
        <h4 style="color:deepskyblue;">动检证</h4>
        <br />
        <hr /><br />
        <el-upload v-model:file-list="fileList" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>
        <br /> <br />
        <h4 style="color:deepskyblue;">企业信息&ensp;&ensp;<el-button @click="Corporationaddtion">设置</el-button></h4>
        <br />
        <hr /><br />
        <el-descriptions column="2">
            <el-descriptions-item label="养殖场：">{{ form1.companyName }}</el-descriptions-item>
            <el-descriptions-item label="负责人：">{{ form1.headOfBreeding }}</el-descriptions-item>
            <el-descriptions-item label="存栏数量：">{{ form1.breedingQuantity }}</el-descriptions-item>
        </el-descriptions>
        <br /> <br />
        <h4 style="color:deepskyblue;">企业照片</h4>
        <br />
        <el-upload v-model:file-list="fileList1" action="http://localhost:5124/api/File/UploadFile"
            list-type="picture-card" :on-preview="handlePictureCardPreview1" :on-remove="handleRemove1"
            :before-upload="beforeAvatarUpload1" :on-success="handleAvatarSuccess1">
            <el-icon>
                <Plus />
            </el-icon>
        </el-upload>

        <!-- 养殖弹框 -->
        <el-dialog v-model="culturedialogVisible" title="养殖信息" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="品种：" prop="breed">
                    <el-input v-model="form.breed" />
                </el-form-item>
                <el-form-item label="来源：" prop="source">
                    <el-input v-model="form.source" />
                </el-form-item>
                <el-form-item label="饲养天数：" prop="feedingDays">
                    <el-input v-model="form.feedingDays" />
                </el-form-item>
                <el-form-item label="饲养品牌：" prop="brand">
                    <el-input v-model="form.brand" />
                </el-form-item>
                <el-form-item label="饲养负责人：" prop="personIncharge">
                    <el-input v-model="form.personIncharge" />
                </el-form-item>
                <el-form-item label="出栏日期：" prop="publicationDate">
                    <el-date-picker v-model="form.publicationDate" type="date" placeholder="请输入出栏日期"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 公司弹框 -->
        <el-dialog v-model="CorporationdialogVisible" title="公司信息" width="500">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="form1" :rules="rules1" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="养殖厂：" prop="companyName">
                    <el-input v-model="form1.companyName" />
                </el-form-item>
                <el-form-item label="负责人：" prop="headOfBreeding">
                    <el-input v-model="form1.headOfBreeding" />
                </el-form-item>
                <el-form-item label="存栏数量（只）：" prop="breedingQuantity">
                    <el-input v-model="form1.breedingQuantity" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="CorporationsubmitForm(ruleFormRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, inject } from 'vue'
import { ErrorTypes, useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, collapseContextKey, type FormInstance, type FormRules } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'

import http from '@/http'
//按钮样式
const buttonsuccess = [
    { type: 'success', text: '保存' },
] as const
const buttoninfo = [
    { type: 'info', text: '取消' },
] as const
const buttondanger = [
    { type: 'danger', text: '删除' },
] as const
const buttonwarning = [
    { type: 'warning', text: '修改' }
] as const

//批次号
const productionLotId = sessionStorage.getItem('productionLot')

//养殖信息弹框值
const culturedialogVisible = ref(false)
//公司信息弹框值
const CorporationdialogVisible = ref(false)

//添加养殖信息弹框
const Sultrueaddtion = () => {
    culturedialogVisible.value = true
}


//养殖数据
const form = reactive({
    cId: 0,
    productionLot: productionLotId,
    farmId: '',
    breed: "",
    source: "",
    dynamicVerification: '',
    publicationDateTime: '',
    feedingDays: '',
    brand: "",
    personIncharge: "",
    publicationDate: "",
})

//回显养殖数据
const GetCultureInfo = () => {
    http.get('/api/Culture/GetCultureInfo?productionLot=' + productionLotId).then(res => {
        let d = res.data

        form.cId = d.cId
        form.breed = d.breed
        form.source = d.source
        form.feedingDays = d.feedingDays == 0 ? null : d.feedingDays
        form.brand = d.brand
        form.farmId = d.farmId
        form.personIncharge = d.personIncharge
        form.publicationDateTime = d.publicationDateTime
        form.publicationDate = d.publicationDate
        form.dynamicVerification = d.dynamicVerification
        getCorporationInfo()
        getPicList1()
    })
}

//添加公司信息弹框
const Corporationaddtion = () => {
    CorporationdialogVisible.value = true
}

//公司数据
const form1 = reactive({
    cId: 0,
    productionLot: productionLotId,
    companyName: "",
    headOfBreeding: "",
    companyPicture: "",
    breedingQuantity: ""
})

//回显公司数据
const getCorporationInfo = () => {
    http.get(`/api/Culture/GetCorporationInfo?productionLot=${productionLotId}&parmId=${form.farmId}`).then(res => {
        let d = res.data
        form1.cId = d.cId
        form1.companyName = d.companyName
        form1.headOfBreeding = d.headOfBreeding
        form1.companyPicture = d.companyPicture
        form1.breedingQuantity = d.breedingQuantity == 0 ? null : d.breedingQuantity
    })
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
//养殖的正则验证
const rules = reactive<FormRules>({
    breed: [
        { required: true, message: '请输入品种', trigger: 'blur' },
    ],
    source: [
        { required: true, message: '请输入来源', trigger: 'blur' },
    ],
    feedingDays: [
        { required: true, message: '请输入饲养天数', trigger: 'blur' },
        { pattern: /^\d{1,5}$/, message: '请输入1-5位正整数', trigger: 'blur' },
    ],
    brand: [
        { required: true, message: '请输入饲养品牌', trigger: 'blur' },
    ],
    personIncharge: [
        { required: true, message: '请输入饲养负责人', trigger: 'blur' },
    ],
    publicationDate: [
        {
            required: true,
            message: '请输入出栏日期',
            trigger: 'change',
        },
    ],
})

//公司的正则验证
const rules1 = reactive<FormRules>({
    companyName: [
        { required: true, message: '请输入养殖场', trigger: 'blur' },
    ],
    headOfBreeding: [
        { required: true, message: '请输入负责人', trigger: 'blur' },
    ],
    breedingQuantity: [
        { required: true, message: '请输入存栏数量', trigger: 'blur' },
        { pattern: /^\d{0,}$/, message: '请输入正整数', trigger: 'blur' },
    ],
})

//添加养殖信息
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (form.cId == 0 || form.cId == undefined) {
                http.post('/api/Culture/AddCultures', form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        culturedialogVisible.value = false
                        GetCultureInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            } else {
                http.put('/api/Culture/UpdateCultures', form).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        culturedialogVisible.value = false
                        GetCultureInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            }
        } else {
        }
    })
}


//添加公司信息
const CorporationsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (form1.cId == 0 || form1.cId == undefined) {
                http.post('/api/Culture/AddCorporation', form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        CorporationdialogVisible.value = false
                        GetCultureInfo()
                        getCorporationInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            } else {
                http.put('/api/Culture/UpdateCorporation', form1).then(res => {
                    if (res.data > 0) {
                        ElMessage.success('保存成功')
                        CorporationdialogVisible.value = false
                        GetCultureInfo()
                        getCorporationInfo()
                    } else {
                        ElMessage.success('保存失败')
                    }
                })
            }
        } else {
        }
    })
}

//动检证图片
const fileList = ref<UploadUserFile[]>([])

//动检
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

//删除动检证
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    handUpLoad(fileList)
}

// 动检证图片判重
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (fileList.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//显示动检证
const getPicList = () => {
    http.get('/api/Culture/GetCulturePicture?productionLot=' + productionLotId).then(res => {
        if (res.data == null) return
        fileList.value = res.data
    })
}

//动检证上传
const handleAvatarSuccess = (data: any) => {
    handUpLoad(fileList)
}

const handUpLoad = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        productionLot: productionLotId,
        urlImg: str,
    }

    http.post('/api/Culture/BatchCulturePicList', info).then(res => {

        if (res.data > 0) {
            GetCultureInfo()
        }
    })
}

//公司图片
const fileList1 = ref<UploadUserFile[]>([])

//公司
const dialogImageUrl1 = ref('')
const dialogVisible1 = ref(false)
const handlePictureCardPreview1: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl1.value = uploadFile.url!
    dialogVisible1.value = true
}

// 公司图片判重
const beforeAvatarUpload1: UploadProps['beforeUpload'] = (rawFile) => {
    if (fileList1.value.findIndex(x => x.name == rawFile.name) != -1) {
        ElMessage({
            type: 'warning',
            message: '该图片已存在！',
            duration: 2000
        });
        return false;
    }
    else {
        return true;
    }
}

//删除公司图片
const handleRemove1: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    handUpLoad1(fileList1)
}

//显示公司图片
const getPicList1 = () => {
    http.get(`/api/Culture/GetCorporationPicture?productionLot=${productionLotId}&parmId=${form.farmId}`).then(res => {
        if (res.data == null) return
        fileList1.value = res.data
    })
}

//公司图片上传
const handleAvatarSuccess1 = (data: any) => {
    handUpLoad1(fileList1)
}

const handUpLoad1 = (list: any) => {
    let str = ''
    list.value.map((x: any) => {
        str += x.name + ','
    })
    str = str.substring(0, str.length - 1)

    let info = {
        productionLot: productionLotId,
        urlImg: str,
        cId: form.cId
    }

    http.post('/api/Culture/BatchCorporationPicList', info).then(res => {
        if (res.data > 0) {
            GetCultureInfo()
        }
    })
}


interface Immune {
    "iId": number,
    "productionLot": string,
    "feedingDays": number,
    "healthCareMode": string,
    "healthCareMethod": string
}

//免疫列表
const immuneList = ref<Immune[]>([]);
//免疫信息
const immuneInfo = reactive({
    "iId": 0,
    "productionLot": productionLotId,
    "feedingDays": "",
    "healthCareMode": "",
    "healthCareMethod": ""
})
//新增行
const NewRow = reactive({
    "iId": 0,
    "productionLot": productionLotId,
    "feedingDays": "",
    "healthCareMode": "",
    "healthCareMethod": "",
    isShow: true
})


var addRowLength = ref(0)

//新增空白行
const addTable = () => {
    if (addRowLength.value + 5 == immuneList.value.length) {
        ElMessage({
            type: 'warning',
            message: '添加的已经够多了，请先完成保存吧！',
            duration: 2000
        })
        return
    }
    immuneInfo.iId = 0;
    immuneInfo.feedingDays = "";
    immuneInfo.healthCareMethod = "";
    immuneInfo.healthCareMode = "";
    immuneInfo.productionLot = productionLotId;
    immuneList.value.push(NewRow) || "";

}

//新增行取消
const DelTable = () => {
    immuneList.value.splice(immuneList.value.length - 1, 1);
}


//免疫信息添加(修改)
const Addimmune = () => {
    if (!Number.isInteger(immuneInfo.feedingDays)) {
        ElMessage.warning('请输入饲养天数,以及合法数字')
    }
    if (!immuneInfo.healthCareMode) {
        ElMessage.warning('请输入保健方式')
        return
    }
    if (!immuneInfo.healthCareMethod) {
        ElMessage.warning('请输入保健方法')
        return
    }
    if (immuneInfo.iId == 0) {
        http.post("/api/Culture/AddImmuneInFormation", immuneInfo).then(res => {
            if (res.data > 0) {
                ElMessage.success("保存成功")
                NewRow.isShow = true
                getimmnueList();
            } else {
                ElMessage.error("保存失败")
            }
        })
    } else {
        http.put("/api/Culture/UpdateImmuneInFormation", immuneInfo).then(res => {
            if (res.data > 0) {
                ElMessage.success("修改成功")
                getimmnueList()
            } else {
                ElMessage.error("修改失败")
            }
        })
    }

}
//免疫信息反填
const getimmuseinfo = (id: number) => {

    NewRow.isShow = false

    http.get("/api/Culture/GetImmuneInFormationInfo?iId=" + id).then(res => {
        immuneInfo.iId = res.data.iId;
        immuneInfo.productionLot = res.data.productionLot;
        immuneInfo.feedingDays = res.data.feedingDays;
        immuneInfo.healthCareMode = res.data.healthCareMode;
        immuneInfo.healthCareMethod = res.data.healthCareMethod;
    })
}

//免疫信息列表
const getimmnueList = () => {
    http.get("/api/Culture/GetImmuneInFormationList?productionLot=" + productionLotId).then(res => {
        immuneList.value = res.data;
        addRowLength.value = res.data.length;
    })
}

//删除免疫
const deltimmnue = (id: number) => {
    ElMessageBox.confirm(
        '确认删除吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            http.delete("/api/Culture/DeleteImmuneInFormation?iId=" + id).then(res => {
                if (res.data > 0) {
                    ElMessage.success("删除成功");
                    getimmnueList();
                } else {
                    ElMessage.error("删除失败");
                }
            })
        })
}

onMounted(() => {
    GetCultureInfo()
    getPicList()
    getimmnueList()
})
</script>

<style scoped></style>